package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"fmt"
)

func ShopBuyItem(u *m.User, typ, tid, num int64, PSend func(interface{}) error) (uProp *m.UpdateProp, resGoods []*m.Goods, boxResList []*m.BoxRes, fResGoods []*m.Goods, shopItem *m.ShopItem, err error) {
	shopItemT, err := m.GetShopItemT(typ, tid)
	if err != nil {
		return
	}
	var cost m.BaseKV

	cost.Key = utils.Int64(shopItemT.Price.Key)
	cost.Val = utils.Int64(shopItemT.Price.Value)

	if err = CheckCost(u, []m.BaseKV{cost}); err != nil {
		return
	}
	fres, shopItem, err := u.GetShopItems().AddItem(typ, tid, num)
	if err != nil {
		return
	}

	uProp, err = Cost("ShopBuyItem", u, []m.BaseKV{cost})
	if err != nil {
		return
	}
	rewards0 := GetBaseKVFromIdKVById(u.MaxPos.LockBlockTid, shopItemT.Goods)
	uProp1, resGoods, BoxResList1, err := GiveGoodsByKvList("ShopBuyItem", u, rewards0, PSend)
	if err != nil {
		return
	}

	boxResList = append(boxResList, BoxResList1...)

	uProp.Merge(uProp1)
	if len(fres) > 0 {
		uProp2, fResGoods1, boxResList2, err := GiveGoodsByKvList("ShopBuyItem", u, GetBaseKVFromIdKVById(u.MaxPos.LockBlockTid, fres), PSend)
		if err != nil {
			return nil, nil, nil, nil, nil, err
		}
		boxResList = append(boxResList, boxResList2...)
		fResGoods = fResGoods1
		uProp.Merge(uProp2)
	}
	return
}

func GetBaseKVFromIdKVById(id int64, list []data.IdKV) (r []m.BaseKV) {
	var baseList []m.BaseKV
	for _, item := range list {
		if item.Id == 0 {
			baseList = append(baseList, m.BaseKV{Key: int64(item.Key), Val: utils.Int64(item.Value)})
		}
		if item.Id == uint64(id) {
			r = append(r, m.BaseKV{Key: int64(item.Key), Val: utils.Int64(item.Value)})
		}
	}
	if len(r) == 0 {
		return baseList
	}
	return
}

func RecordShopBuyItem(u *m.User, paiPropsId int64) (err error) {
	tplLst, ok := data.Filters("ShopDiamonds", func(val interface{}) bool {
		valT := val.(data.RechargeItem)
		return int64(valT.PaiPropsId) == paiPropsId
	})
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到激活活动配置,ShopDiamonds")
		return
	}
	if tplLst == nil || len(tplLst) == 0 {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("没有该数据，paiPropsId:%d", paiPropsId))
		return
	}
	tplT := tplLst[0].(data.RechargeItem)

	si := u.GetShopItems()
	defer si.Update(si)

	tid := int64(tplT.Id)
	v, ok := si.Items[tid]

	if !ok {
		v = &m.ShopItem{
			Tid: tid,
			Typ: int64(tplT.Type),
			Num: 0,
		}
		si.Items[tid] = v
	}
	nowUnix := utils.TNow().Unix()
	// 不是同一天，更新购买次数
	if !utils.IsSameDay(v.Time, nowUnix) {
		v.Num = 0
	}
	if v.Num > 99 {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("购买钻石次数超过限制，ShopDiamondsTid:%d", tid))
		return
	}
	// 增加购买次数
	v.Num += 1
	v.Time = nowUnix
	return
}

func GetShopItems(u *m.User) (r *m.ShopItems) {
	si := u.GetShopItems()
	nowUnix := utils.TNow().Unix()
	for _, item := range si.Items {
		// 不是同一天，重置购买次数
		if !utils.IsSameDay(item.Time, nowUnix) {
			item.Time = nowUnix
			item.Num = 0
		}
	}
	si.Update(si)
	return si
}

// 直接购买道具
func DirectlyBuy(from string, us *m.User, tid int64, PSend func(interface{}) error) (uProp *m.UpdateProp, resGoods []*m.Goods, boxResList []*m.BoxRes, err error) {
	tpl, ok := data.Get("DirectlyBuys", uint64(tid))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有该配表DirectlyBuys，或者该表没有索引为1的数据"))
		return
	}
	tplT := tpl.(data.DirectlyBuy)
	var goods data.IdKV

	lockBlockTid := us.MaxPos.LockBlockTid
	lenght := len(tplT.Goods)
	switch tid {
	case 1: // 钻石购买金币
		if lockBlockTid >= int64(lenght) {
			err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("DirectlyBuys该道具的长度没有玩家最大关卡大，lockBlockTid：%d，lenght：%d", lockBlockTid, lenght))
			return
		}
		// 根据玩家的最大关卡，获取相应的道具
		goods = tplT.Goods[lockBlockTid]
	case 2: // 钻石购买饲料
		if lenght <= 0 {
			err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("DirectlyBuys没有饲料道具数据 %d", tid))
			return
		}
		goods = tplT.Goods[0]
	case 1000: // 好友分享奖励
		if lenght <= 0 {
			err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("DirectlyBuys没有饲料道具数据 %d", tid))
			return
		}
		goods = tplT.Goods[0]
		limitNum := int64(goods.Id)
		if err = RecordShareNum(us, limitNum); err != nil {
			return
		}
	}
	cost := m.BaseKV{
		Key: int64(tplT.PriceScale.Key),
		Val: int64(tplT.PriceScale.Value),
	}
	// 扣去玩家身上的道具
	uProp1, err := Cost(from, us, []m.BaseKV{cost})
	if err != nil {
		return
	}
	// 给玩家道具
	uProp, resGoods, boxResList, err = GiveGoodsByKv(from, us, m.BaseKV{Key: int64(goods.Key), Val: int64(goods.Value)}, PSend)
	if err != nil {
		return
	}
	uProp.Merge(uProp1)
	return
}
